package com.zeus.base.smscenter.controller;

import com.alibaba.fastjson.JSON;
import com.zeus.base.privilege.model.TbUser;
import com.zeus.base.privilege.utils.IdWorkerTools;
import com.zeus.base.privilege.utils.ResultModel;
import com.zeus.base.privilege.utils.StringUtil;
import com.zeus.base.smscenter.common.BaseController;
import com.zeus.base.smscenter.model.SmsSupplier;
import com.zeus.base.smscenter.model.SmsSupplierProperty;
import com.zeus.base.smscenter.model.Tenant;
import com.zeus.base.smscenter.service.ISmsSettingService;
import com.zeus.base.smscenter.service.ISupplierPropertyService;
import com.zeus.base.smscenter.service.ISupplierService;
import com.zeus.base.smscenter.utils.SessionUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 供应商信息设定Controller
 */
@SuppressWarnings("ALL")
@RestController
@RequestMapping("/controller/supplier")
public class SupplierController extends BaseController {
    @Autowired
    private ISupplierService iSupplierService;
    @Autowired
    private ISmsSettingService iSmsSettingService;

    @Autowired
    private ISupplierPropertyService iSupplierPropertyService;

    /**
     * 获取应用系统(默认参数,Add页面调用)
     *
     * @param keyId
     * @return
     */
    @RequestMapping(value = "/default", method = RequestMethod.POST)
    @ResponseBody
    public SmsSupplier getAddDefaultSmsSupplier(String keyId){
        return null;
    }

    /**
     * 获取租户Code
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTenantCode", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<ResultModel> getTenantCode(HttpServletRequest request){

        TbUser loginUser = SessionUtil.getSessionUser(request);
        ResponseEntity<ResultModel> resultModel = new ResponseEntity<ResultModel>(new ResultModel(true,loginUser.getCompanyCodes()), HttpStatus.OK);
        return resultModel;
    }

    /**
     * 获取租户信息
     *
     * @param keyId
     * @param request
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseBody
    public SmsSupplier getSmsSupplier(String keyId,HttpServletRequest request){

        SmsSupplier smsSupplier = iSupplierService.selectByPrimaryKey(keyId);
        StringBuffer sb = new StringBuffer();
        SmsSupplierProperty smsSupplierPropertyCond = new SmsSupplierProperty();
        smsSupplierPropertyCond.setTenantCode(smsSupplier.getTenantCode());
        smsSupplierPropertyCond.setSupplierNo(smsSupplier.getSupplierNo());
        smsSupplier.setPropertyLst(iSupplierPropertyService.selectByCodeSuppNo(smsSupplierPropertyCond));
        Map map = new HashMap();
        map.put("rows", smsSupplier.getPropertyLst());
        smsSupplier.setRemark(JSON.toJSONString(map));
        return smsSupplier;
    }

    /**
     * 添加保存
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterSupplierManager:add")
    public ResponseEntity<ResultModel> save(SmsSupplier supplier, HttpServletRequest request) {
        ResponseEntity responseEntity = new ResponseEntity<ResultModel>(new ResultModel(false,"操作保存失败"), HttpStatus.OK);
        ResponseEntity responseSuccessEntity = new ResponseEntity<ResultModel>(new ResultModel(true,"操作保存成功"), HttpStatus.OK);

        if (supplier != null) {
            //添加之前先确认租户信息已经设置完毕,未设置的时候,提示先设置,本次添加失败.
            Tenant tenant = iSmsSettingService.selectByCode(supplier.getTenantCode());
            if(tenant==null){
                ResultModel resultModel = new ResultModel(false);
                resultModel.setMessage("请先设置租户信息,再添加供应商信息!");
                resultModel.setSuccess(false);
                return new ResponseEntity<ResultModel>(resultModel, HttpStatus.OK);
            }
            //添加之前先确认本次所选择的供应商是否已经存在,如果存在则不重复添加.否则进行添加处理.
            SmsSupplier supplierExist = iSupplierService.existByCodeSuppNoAppForm(supplier);
            if(supplierExist!=null && !StringUtil.isEmpty(supplierExist.getId())){
                ResultModel resultModel = new ResultModel(false);
                resultModel.setMessage("供应商信息已经存在,请勿重复添加!");
                resultModel.setSuccess(false);
                return new ResponseEntity<ResultModel>(resultModel, HttpStatus.OK);
            }
            //供应商设置
            if(StringUtil.isEmpty(supplier.getId())){
                supplier.setId(IdWorkerTools.getInstance().getId().toString());
            }
            supplier.setDelFlag(0);
            supplier.setCreateTime(new Date());

            ResultModel resultModel = iSupplierService.insert(supplier);
            if(resultModel.isSuccess()){
                //供应商属性设置
                if(supplier.getPropertyLst()!=null && supplier.getPropertyLst().size() >0){
                    List<SmsSupplierProperty> propertyList = new ArrayList<SmsSupplierProperty>();
                    for(SmsSupplierProperty smsSupplierProperty : supplier.getPropertyLst()) {
                        smsSupplierProperty.setId(IdWorkerTools.getInstance().getId().toString());
                        smsSupplierProperty.setIsUsed("Y");
                        smsSupplierProperty.setTenantCode(supplier.getTenantCode());
                        smsSupplierProperty.setSupplierType(supplier.getSupplierNo());
                        smsSupplierProperty.setSupplierNo(supplier.getSupplierNo());
                        smsSupplierProperty.setCreateTime(supplier.getCreateTime());
                        propertyList.add(smsSupplierProperty);
                        resultModel = iSupplierPropertyService.insert(smsSupplierProperty);
                        if(resultModel.isSuccess()){
                            continue;
                        }else{
                            return responseEntity;
                        }
                    }
                    supplier.setPropertyLst(propertyList);
                    return responseSuccessEntity;
                }
            }else{
                return responseEntity;
            }
        }
        return responseEntity;
    }

    /**
     * 修改保存
     *
     * @param company
     * @param request
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterSupplierManager:update")
    public ResponseEntity<ResultModel> update(SmsSupplier supplier, HttpServletRequest request) {
        ResponseEntity responseEntity = new ResponseEntity<ResultModel>(new ResultModel(false,"操作保存失败"), HttpStatus.OK);
        ResponseEntity responseSuccessEntity = new ResponseEntity<ResultModel>(new ResultModel(true,"操作保存成功"), HttpStatus.OK);
        if (supplier != null) {
            //供应商设置
            if(StringUtil.isEmpty(supplier.getId())){
                supplier.setId(IdWorkerTools.getInstance().getId().toString());
            }
            supplier.setDelFlag(0);
            supplier.setUpdateTime(new Date());

            ResultModel resultModel = iSupplierService.update(supplier);
            if(resultModel.isSuccess()){
                //原有的供应商属性信息,先全部删除后,再重新添加最新的数据.
                if(StringUtil.isNotEmpty(supplier.getTenantCode()) && StringUtil.isNotEmpty(supplier.getSupplierNo())){
                    SmsSupplierProperty  smsSupplierPropertyCond = new SmsSupplierProperty();
                    smsSupplierPropertyCond.setTenantCode(supplier.getTenantCode());
                    smsSupplierPropertyCond.setSupplierNo(supplier.getSupplierNo());
                    resultModel = iSupplierPropertyService.deleteByCodeSuppNo(smsSupplierPropertyCond);
                }else{
                    return responseEntity;
                }

                //供应商属性设置
                if(supplier.getPropertyLst()!=null && supplier.getPropertyLst().size() >0){
                    List<SmsSupplierProperty> propertyList = new ArrayList<SmsSupplierProperty>();
                    for(SmsSupplierProperty smsSupplierProperty : supplier.getPropertyLst()) {
                        smsSupplierProperty.setId(IdWorkerTools.getInstance().getId().toString());
                        smsSupplierProperty.setIsUsed("Y");
                        smsSupplierProperty.setTenantCode(supplier.getTenantCode());
                        smsSupplierProperty.setSupplierType(supplier.getSupplierNo());
                        smsSupplierProperty.setSupplierNo(supplier.getSupplierNo());
                        smsSupplierProperty.setCreateTime(supplier.getCreateTime());
                        propertyList.add(smsSupplierProperty);
                        resultModel = iSupplierPropertyService.insert(smsSupplierProperty);
                        if(resultModel.isSuccess()){
                            continue;
                        }else{
                            return responseEntity;
                        }
                    }
                    supplier.setPropertyLst(propertyList);
                    return responseSuccessEntity;
                }
            }else{
                return responseEntity;
            }
        }
        return responseEntity;
    }

    /**
     * 删除
     *
     * @param keyId
     * @param request
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterSupplierManager:delete")
    public ResponseEntity<ResultModel> delete(String keyId, HttpServletRequest request) {
        if (keyId != null && StringUtil.isNotEmpty(keyId)) {
            return new ResponseEntity<ResultModel>(iSupplierService.deleteByKeyId(keyId), HttpStatus.OK);
        }
        return new ResponseEntity<ResultModel>(new ResultModel(false), HttpStatus.OK);
    }

    /**
     * 批量删除
     *
     * @param keyIds
     * @param request
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("SmsCenterSupplierManager:delete")
    public ResponseEntity<ResultModel> batchDelete(String keyIds, HttpServletRequest request) {
        if (StringUtil.isNotEmpty(keyIds)) {
            return new ResponseEntity<ResultModel>(iSupplierService.batchDelete(keyIds.split(",")), HttpStatus.OK);
        }
        return new ResponseEntity<ResultModel>(new ResultModel(false), HttpStatus.OK);
    }
}
